// Package user 存放用户 Model 相关逻辑
package models

import (
	"books/pkg/database"
)

// User 用户模型
type User struct {
	BaseModel

	Name        string `json:"name,omitempty"`
	Email       string `json:"email,omitempty"`
	BorrowCount int    `json:"borrow_count"`
	Password    string `json:"-"`

	CommonTimestampsField
}

func GetUsers(name, email string) ([]User, error) {
	var users []User
	db := database.DB.Model(User{})

	if name != "" {
		db = db.Where("name LIKE ?", "%"+name+"%")
	}
	if email != "" {
		db = db.Where("email LIKE ?", "%"+email+"%")
	}

	err := db.Order("id desc").Find(&users).Error

	return users, err
}

func GetUser(id uint64) (*User, error) {
	user := &User{}

	err := database.DB.Model(User{}).Where("id = ?", id).First(&user).Error

	return user, err
}

func (user *User) CreateUser() error {
	err := database.DB.Create(&user).Error
	return err
}

func (user *User) Save() error {
	err := database.DB.Save(&user).Error
	return err
}
